// SmartInput Chrome扩展设置页面脚本
class SmartInputOptions {
  constructor() {
    this.settings = {};
    this.isEditingShortcut = false;
    this.currentShortcutTarget = null;
    
    this.init();
  }
  
  async init() {
    console.log('SmartInput设置页面初始化...');
    
    // 获取DOM元素
    this.getElements();
    
    // 设置事件监听器
    this.setupEventListeners();
    
    // 加载设置
    await this.loadSettings();
    
    // 更新UI
    this.updateUI();
  }
  
  getElements() {
    // 基本设置
    this.apiBase = document.getElementById('apiBase');
    this.wsBase = document.getElementById('wsBase');
    this.deviceName = document.getElementById('deviceName');
    this.autoConnect = document.getElementById('autoConnect');
    
    // 语音设置
    this.voiceEnabled = document.getElementById('voiceEnabled');
    this.voiceLanguage = document.getElementById('voiceLanguage');
    this.voiceConfidence = document.getElementById('voiceConfidence');
    this.confidenceValue = document.getElementById('confidenceValue');
    this.autoInsert = document.getElementById('autoInsert');
    
    // 同步设置
    this.syncEnabled = document.getElementById('syncEnabled');
    this.syncTarget = document.getElementById('syncTarget');
    this.syncNotification = document.getElementById('syncNotification');
    
    // 界面设置
    this.theme = document.getElementById('theme');
    this.showFloatingPanel = document.getElementById('showFloatingPanel');
    this.showVoiceButton = document.getElementById('showVoiceButton');
    this.panelPosition = document.getElementById('panelPosition');
    
    // 快捷键设置
    this.voiceShortcut = document.getElementById('voiceShortcut');
    this.syncShortcut = document.getElementById('syncShortcut');
    
    // 账户设置
    this.userName = document.getElementById('username');
    this.password = document.getElementById('password');
    this.loginBtn = document.getElementById('loginBtn');
    this.logoutBtn = document.getElementById('logoutBtn');
    
    // 高级设置
    this.debugMode = document.getElementById('debugMode');
    this.logLevel = document.getElementById('logLevel');
    this.exportBtn = document.getElementById('exportBtn');
    this.importBtn = document.getElementById('importBtn');
    this.resetBtn = document.getElementById('resetBtn');
    
    // 底部按钮
    this.saveBtn = document.getElementById('saveBtn');
    this.cancelBtn = document.getElementById('cancelBtn');
  }
  
  setupEventListeners() {
    // 保存按钮
    this.saveBtn.addEventListener('click', () => {
      this.saveSettings();
    });
    
    // 取消按钮
    this.cancelBtn.addEventListener('click', () => {
      window.close();
    });
    
    // 登录按钮
    this.loginBtn.addEventListener('click', () => {
      this.login();
    });
    
    // 登出按钮
    this.logoutBtn.addEventListener('click', () => {
      this.logout();
    });
    
    // 导出按钮
    this.exportBtn.addEventListener('click', () => {
      this.exportSettings();
    });
    
    // 导入按钮
    this.importBtn.addEventListener('click', () => {
      this.importSettings();
    });
    
    // 重置按钮
    this.resetBtn.addEventListener('click', () => {
      this.resetSettings();
    });
    
    // 快捷键编辑按钮
    document.querySelectorAll('.edit-shortcut-btn').forEach(btn => {
      btn.addEventListener('click', (e) => {
        this.startShortcutEditing(e.target.dataset.target);
      });
    });
    
    // 置信度滑块
    this.voiceConfidence.addEventListener('input', (e) => {
      this.confidenceValue.textContent = e.target.value;
    });
    
    // 设置依赖关系
    this.setupDependencies();
  }
  
  setupDependencies() {
    // 语音设置依赖
    this.voiceEnabled.addEventListener('change', () => {
      this.updateVoiceSettingsVisibility();
    });
    
    // 同步设置依赖
    this.syncEnabled.addEventListener('change', () => {
      this.updateSyncSettingsVisibility();
    });
    
    // 浮动面板依赖
    this.showFloatingPanel.addEventListener('change', () => {
      this.updatePanelSettingsVisibility();
    });
  }
  
  updateVoiceSettingsVisibility() {
    const voiceSettings = document.querySelectorAll('.setting-group');
    voiceSettings.forEach(setting => {
      if (setting.querySelector('#voiceLanguage') || 
          setting.querySelector('#voiceConfidence') ||
          setting.querySelector('#autoInsert')) {
        if (this.voiceEnabled.checked) {
          setting.classList.remove('disabled');
        } else {
          setting.classList.add('disabled');
        }
      }
    });
  }
  
  updateSyncSettingsVisibility() {
    const syncSettings = document.querySelectorAll('.setting-group');
    syncSettings.forEach(setting => {
      if (setting.querySelector('#syncTarget') || 
          setting.querySelector('#syncNotification')) {
        if (this.syncEnabled.checked) {
          setting.classList.remove('disabled');
        } else {
          setting.classList.add('disabled');
        }
      }
    });
  }
  
  updatePanelSettingsVisibility() {
    const panelSettings = document.querySelectorAll('.setting-group');
    panelSettings.forEach(setting => {
      if (setting.querySelector('#panelPosition')) {
        if (this.showFloatingPanel.checked) {
          setting.classList.remove('disabled');
        } else {
          setting.classList.add('disabled');
        }
      }
    });
  }
  
  async loadSettings() {
    try {
      // 加载统一配置
      await smartInputConfig.loadFromStorage();
      this.settings = smartInputConfig.getAll();
      
    } catch (error) {
      console.error('加载设置失败:', error);
      this.showNotification('加载设置失败', 'error');
    }
  }
  
  updateUI() {
    // 更新表单值
    this.apiBase.value = this.settings.apiBase;
    this.wsBase.value = this.settings.wsBase;
    this.deviceName.value = this.settings.deviceName;
    this.autoConnect.checked = this.settings.autoConnect;
    this.voiceEnabled.checked = this.settings.voiceEnabled;
    this.voiceLanguage.value = this.settings.voiceLanguage;
    this.voiceConfidence.value = this.settings.voiceConfidence;
    this.confidenceValue.textContent = this.settings.voiceConfidence;
    this.autoInsert.checked = this.settings.autoInsert;
    this.syncEnabled.checked = this.settings.syncEnabled;
    this.syncTarget.value = this.settings.syncTarget;
    this.syncNotification.checked = this.settings.syncNotification;
    this.theme.value = this.settings.theme;
    this.showFloatingPanel.checked = this.settings.showFloatingPanel;
    this.showVoiceButton.checked = this.settings.showVoiceButton;
    this.panelPosition.value = this.settings.panelPosition;
    this.voiceShortcut.value = this.settings.voiceShortcut;
    this.syncShortcut.value = this.settings.syncShortcut;
    this.userName.value = this.settings.userName || '';
    this.debugMode.checked = this.settings.debugMode;
    this.logLevel.value = this.settings.logLevel;
    
    // 更新依赖关系
    this.updateVoiceSettingsVisibility();
    this.updateSyncSettingsVisibility();
    this.updatePanelSettingsVisibility();
  }
  
  async saveSettings() {
    try {
      this.saveBtn.disabled = true;
      this.saveBtn.textContent = '保存中...';
      
      // 收集设置值
      const newSettings = {
        apiBase: this.apiBase.value,
        wsBase: this.wsBase.value,
        deviceName: this.deviceName.value,
        autoConnect: this.autoConnect.checked,
        voiceEnabled: this.voiceEnabled.checked,
        voiceLanguage: this.voiceLanguage.value,
        voiceConfidence: parseFloat(this.voiceConfidence.value),
        autoInsert: this.autoInsert.checked,
        syncEnabled: this.syncEnabled.checked,
        syncTarget: this.syncTarget.value,
        syncNotification: this.syncNotification.checked,
        theme: this.theme.value,
        showFloatingPanel: this.showFloatingPanel.checked,
        showVoiceButton: this.showVoiceButton.checked,
        panelPosition: this.panelPosition.value,
        voiceShortcut: this.voiceShortcut.value,
        syncShortcut: this.syncShortcut.value,
        debugMode: this.debugMode.checked,
        logLevel: this.logLevel.value
      };
      
      // 更新统一配置
      await smartInputConfig.update(newSettings);
      
      // 通知background script更新配置
      await chrome.runtime.sendMessage({
        action: 'updateConfig',
        config: newSettings
      });
      
      this.settings = newSettings;
      
      this.showNotification('设置已保存', 'success');
      
      // 延迟关闭窗口
      setTimeout(() => {
        window.close();
      }, 1500);
      
    } catch (error) {
      console.error('保存设置失败:', error);
      this.showNotification('保存设置失败', 'error');
    } finally {
      this.saveBtn.disabled = false;
      this.saveBtn.textContent = '保存设置';
    }
  }
  
  async login() {
    try {
      const userName = this.userName.value.trim();
      const password = this.password.value.trim();
      
      if (!userName || !password) {
        this.showNotification('请输入用户名和密码', 'warning');
        return;
      }
      
      this.loginBtn.disabled = true;
      this.loginBtn.textContent = '登录中...';
      
      await chrome.runtime.sendMessage({
        action: 'login',
        credentials: { userName, password }
      });
      
      this.showNotification('登录成功', 'success');
      
      // 清空密码字段
      this.password.value = '';
      
    } catch (error) {
      console.error('登录失败:', error);
      this.showNotification('登录失败: ' + error.message, 'error');
    } finally {
      this.loginBtn.disabled = false;
      this.loginBtn.textContent = '登录';
    }
  }
  
  async logout() {
    try {
      await chrome.runtime.sendMessage({ action: 'logout' });
      
      this.userName.value = '';
      this.password.value = '';
      
      this.showNotification('已登出', 'info');
      
    } catch (error) {
      console.error('登出失败:', error);
      this.showNotification('登出失败', 'error');
    }
  }
  
  async exportSettings() {
    try {
      const settings = await chrome.storage.local.get(null);
      const dataStr = JSON.stringify(settings, null, 2);
      const dataBlob = new Blob([dataStr], { type: 'application/json' });
      
      const url = URL.createObjectURL(dataBlob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `smartinput-settings-${new Date().toISOString().split('T')[0]}.json`;
      link.click();
      
      URL.revokeObjectURL(url);
      
      this.showNotification('设置已导出', 'success');
      
    } catch (error) {
      console.error('导出设置失败:', error);
      this.showNotification('导出设置失败', 'error');
    }
  }
  
  async importSettings() {
    try {
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = '.json';
      
      input.onchange = async (e) => {
        const file = e.target.files[0];
        if (!file) return;
        
        const reader = new FileReader();
        reader.onload = async (e) => {
          try {
            const settings = JSON.parse(e.target.result);
            
            // 验证设置格式
            if (typeof settings !== 'object') {
              throw new Error('无效的设置文件格式');
            }
            
            // 保存设置
            await chrome.storage.local.set(settings);
            
            // 重新加载设置
            await this.loadSettings();
            this.updateUI();
            
            this.showNotification('设置已导入', 'success');
            
          } catch (error) {
            console.error('解析设置文件失败:', error);
            this.showNotification('设置文件格式错误', 'error');
          }
        };
        
        reader.readAsText(file);
      };
      
      input.click();
      
    } catch (error) {
      console.error('导入设置失败:', error);
      this.showNotification('导入设置失败', 'error');
    }
  }
  
  async resetSettings() {
    try {
      if (!confirm('确定要重置所有设置吗？此操作不可撤销。')) {
        return;
      }
      
      // 清除所有设置
      await chrome.storage.local.clear();
      
      // 重新加载默认设置
      await this.loadSettings();
      this.updateUI();
      
      this.showNotification('设置已重置', 'info');
      
    } catch (error) {
      console.error('重置设置失败:', error);
      this.showNotification('重置设置失败', 'error');
    }
  }
  
  startShortcutEditing(target) {
    if (this.isEditingShortcut) return;
    
    this.isEditingShortcut = true;
    this.currentShortcutTarget = target;
    
    const input = document.getElementById(target);
    input.classList.add('shortcut-editing');
    input.focus();
    input.select();
    
    // 监听键盘事件
    const handleKeyDown = (e) => {
      e.preventDefault();
      
      const keys = [];
      if (e.ctrlKey) keys.push('Ctrl');
      if (e.shiftKey) keys.push('Shift');
      if (e.altKey) keys.push('Alt');
      if (e.metaKey) keys.push('Cmd');
      
      if (e.key !== 'Control' && e.key !== 'Shift' && e.key !== 'Alt' && e.key !== 'Meta') {
        keys.push(e.key.toUpperCase());
      }
      
      if (keys.length > 0) {
        input.value = keys.join('+');
        this.stopShortcutEditing();
      }
    };
    
    const handleBlur = () => {
      this.stopShortcutEditing();
    };
    
    input.addEventListener('keydown', handleKeyDown);
    input.addEventListener('blur', handleBlur);
    
    // 保存事件处理器引用以便移除
    this.shortcutEventHandlers = { handleKeyDown, handleBlur };
  }
  
  stopShortcutEditing() {
    if (!this.isEditingShortcut) return;
    
    const input = document.getElementById(this.currentShortcutTarget);
    input.classList.remove('shortcut-editing');
    
    if (this.shortcutEventHandlers) {
      input.removeEventListener('keydown', this.shortcutEventHandlers.handleKeyDown);
      input.removeEventListener('blur', this.shortcutEventHandlers.handleBlur);
      this.shortcutEventHandlers = null;
    }
    
    this.isEditingShortcut = false;
    this.currentShortcutTarget = null;
  }
  
  showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.textContent = message;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
      if (notification.parentNode) {
        notification.remove();
      }
    }, 3000);
  }
}

// 初始化设置页面
document.addEventListener('DOMContentLoaded', () => {
  new SmartInputOptions();
}); 